package com.romotc.qqrobot.webqq.qqInterfaceLog;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.romotc.oschina.db.DBManager;
import com.romotc.qqrobot.bean.QQData;
import com.romotc.qqrobot.bean.QQInfoFromQQLogedin;
import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.bean.QQUserFriend;
import com.romotc.qqrobot.config.QQUrlWatcherConfigService;
import com.romotc.qqrobot.config.bean.QQUrlWatcherConfig;
import com.romotc.scache.RequestSpy;
import com.romotc.scache.mgr;

/**
 * webQQ接口返回数据记录线程类
 * @author Administrator
 *
 */
public class QQInterfaceLog implements Runnable {

	private RequestSpy rqSpy;
	private static List<QQUrlWatcherConfig> urlConfigs;
	
	static {
		getAllUrlConfig();
	}
	
	public static void getAllUrlConfig()
	{
		urlConfigs = QQUrlWatcherConfigService.getAllConfigs();
	}

	public void run() {
		if(rqSpy == null) {
			return;
		}
		
		boolean defautlLoged = false;//已经使用默认日志记录过
		for(QQUrlWatcherConfig config : urlConfigs) {
			if(config.getUrl() == null || "".equals(config.getUrl())) {
				continue;
			}
			
			if(mgr.simpleWildMatch(config.getUrl(), rqSpy.getURL()) != null) {
				try {
					if(config.getLogClass() == null 
							|| "".equals(config.getLogClass().trim())
							|| config.getLogClass().startsWith("#")) {
						config.setLogClass("com.romotc.qqrobot.webqq.qqInterfaceLog.DefaultUrl_Log");
						if(defautlLoged)
							continue;
						else
							defautlLoged = true;
					}
					QQUrlLogInterface qqurlLog = QQUrlLogFactory.getQQUrlLog(config.getLogClass());
					System.out.println("log::Run [" + config.getLogClass() +"] for " + rqSpy.getURL());
					if(!qqurlLog.logRequestSpy(rqSpy, config))
						break;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		
		
//		QQData qData = QQData.buildQQTransData(rqSpy);
//		if(qData != null)
//			qData.Save();
		
//		//如果是QQ登录事件
//		if(rqSpy.getURL().indexOf(QQData.URL_LOGIN2) != -1) {
//			//创建QQLogedIn对象 缓存到程序中以便后续主动发起请求；并记录到数据库中
//			QQLogedin qqLogedIn = QQLogedin.buildQQLogedIn(rqSpy);
//		}else if (rqSpy.getURL().indexOf(QQData.URL_GET_FRIEND_INFO2) != -1) {
//			//构造此Qq所能获取到的 某QQ号码的信息
//			QQInfoFromQQLogedin qqInfo = QQInfoFromQQLogedin.buildQQInfo(rqSpy);
//		}else if(rqSpy.getURL().indexOf(QQData.URL_GET_USER_FRIENDS) != -1){
//			//获取到的好友信息
//			List<QQUserFriend> qqUserFriends = QQUserFriend.buildQQUserFriends(rqSpy); 
//		}
		
		//DBManager.closeConnection();
	}

	public QQInterfaceLog(RequestSpy rqSpy) {
		this.rqSpy = rqSpy;
	}
}
